package com.marketingexpert.controller.marketingmgnt.activityrecomment;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import com.marketingexpert.config.Placeholder;
import com.marketingexpert.config.SystemErrorCode;
import com.marketingexpert.domain.User;
import com.marketingexpert.exception.MarketingExpertException;
import com.marketingexpert.service.marketingmgnt.MarketingService;
import com.marketingexpert.service.storemgnt.MarketingPromotion;
import com.marketingexpert.util.FillPlaceholder;
import com.marketingexpert.util.Resources;
import com.marketingexpert.util.WebUtils;
import com.taobao.api.domain.Meal;

public class QueryMealController implements Controller {

	private MarketingService marketingService;	
	
	private SystemErrorCode systemErrorCode;
	
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String type = request.getParameter("type");
		String dispatchUrl = request.getParameter("dispatchUrl");
		String sessionKey = (String) request.getSession().getAttribute("taobaoSessionKey");		
try {	
			List<Meal> meals = marketingService.queryMeals(-1L, sessionKey);
			
			if(meals == null || meals.size() <= 0) {
				return new ModelAndView(dispatchUrl, "meals", null);
			}
			
			for(int i=0; i<meals.size(); i++) {
				Meal _m = meals.get(i);
				_m.setMealPrice(FillPlaceholder.formateStr(_m.getMealPrice()));
				meals.set(i, _m);
			}			
			return new ModelAndView(dispatchUrl, "meals", meals);			
		} catch(MarketingExpertException e) {
			
			if(e.getErrCode().equals(systemErrorCode.getInvalidSession()) || e.getErrCode().equals(systemErrorCode.getTaobaoExpiredSession())) {
				request.getSession().removeAttribute("taobaoSessionKey");
				request.getSession().removeAttribute("parentUserId");
				request.getSession().setAttribute("sessionExpired", Resources.getString("InvalidSession"));
				response.sendRedirect(WebUtils.getBasepath(request) + "/pages/sessionExpiredTip.jsp");
				return null;
			}
			return new ModelAndView(dispatchUrl, "Failed", Resources.getString("QueryMealController.getMealFailed"));
		}	
	}

	public MarketingService getMarketingService() {
		return marketingService;
	}

	public void setMarketingService(MarketingService marketingService) {
		this.marketingService = marketingService;
	}

	public SystemErrorCode getSystemErrorCode() {
		return systemErrorCode;
	}

	public void setSystemErrorCode(SystemErrorCode systemErrorCode) {
		this.systemErrorCode = systemErrorCode;
	}

	
}
